<template>
    <div class="crop">
        <div>
            <el-form ref="form" label-width="80px" :model="formData" class="inputs">
                <el-form-item label="高度">
                    <el-input v-model="formData.height" disabled placeholder="" class="input"></el-input>
                </el-form-item>
                <el-form-item label="宽度">
                    <el-input v-model="formData.width" disabled placeholder="" class="input"></el-input>
                </el-form-item>
            </el-form>
        </div>
        <img :src="url" alt="" class="img" ref="img">
    </div>
</template>

<script>
import 'cropperjs/dist/cropper.min.css'
import Cropper from 'cropperjs'
export default {
    name:'Crop',
    data() {
        return {
            cropper:null,
            formData:{
                height:0,//当前的宽度
                width:0,//当前的高度
            },
            url:'',//显示图片链接
        }
    },
    watch:{
        url(newValue){
            this.$nextTick(()=>{
                const image = this.$refs.img
                //使用that保存vue，方便后续进行访问
                let that = this
                if(this.cropper){
                    //如果已经有实例了，先销毁实例，不然会导致图片无法更新
                    this.cropper.destroy();
                }
                this.cropper = new Cropper(image, {
                    viewMode:1,
                    dragMode:"move",
                    autoCropArea:0.9,
                    crop(event) {
                        that.formData.height = Math.ceil(event.detail.height)
                        that.formData.width = Math.ceil(event.detail.width)
                    },
                })
            })
            
        }
    },
    mounted(){
        
    },
    methods:{
        getData(){
            // console.log(this.cropper.getCroppedCanvas().toDataURL('image/png'))
            let dataURL = this.cropper.getCroppedCanvas().toDataURL('image/png')
            let blob = this.baseImg(dataURL)
            // console.log(blob)
            // console.log(URL.createObjectURL(blob))
            return {
                file:blob,
                url:URL.createObjectURL(blob)
            }
        },
        //将base64转为图片文件
        baseImg (dataurl) {
            var arr = dataurl.split(','),
            mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]),n = bstr.length,
            u8arr = new Uint8Array(n);
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n)
            }
            return new Blob([u8arr], {type: mime})
        },
    }
}
</script>

<style lang="scss" scoped>
.crop{
    width: 100%;
    overflow: hidden;
    .img{
        width: 100%;
    }
}

.inputs{
    display: flex;
    justify-content: center;
    .input{
        width: 70px;
    }
}
</style>